package com.example.experiment03.service;

import com.example.experiment03.entity.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class DataService implements InitializingBean {
    List<RegionStats> list = new ArrayList<>();
    final String DATA_URL="https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    public List<RegionStats> getList()
    {
        return list;
    }


    /**
     *每天早上8点执行计划任务，更新list成员变量
     *list成员变量储存全球新型冠状病毒统计数据
     *
     * @throws IOException IO异常
     */
    @Scheduled(cron = "0 0 8 * * *")
    public void fetchVirusData() throws IOException{
        if (!list.isEmpty()){
            list.clear();
        }

        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();

        final Reader reader = newReader(Objects.requireNonNull(body).getInputStream());
        final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
        try {
            for (CSVRecord record : parser){
                String state = record.get("Province/State");
                String country = record.get("Country/Region");
                int last = Integer.parseInt(record.get(record.size()-1));
                int prev = Integer.parseInt(record.get(record.size()-2));

                RegionStats regionStats = new RegionStats(state,country,last,last-prev);
                list.add(regionStats);

            }

        }finally {
            parser.close();
            reader.close();
        }

    }
    /**
     * Creates a reader capable of handling BOMs.
     */
    public InputStreamReader newReader(final InputStream inputStream) {
        return new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    }

    @Override
    public void afterPropertiesSet() throws Exception{
        fetchVirusData();
    }

    /**
     * 获取全球确诊总数量和新增确诊总数
     */
    public Integer getTotalConfirmed(List<RegionStats> list){

        return list.stream().mapToInt(RegionStats::getLatestTotalCases).sum();
    }

    public Integer getIncreasedConfirmed(List<RegionStats> list){

        return list.stream().mapToInt(RegionStats::getDiffFromPrevDay).sum();
    }

    /**
     * 获得某一国家的疫情数据*/
    public List<RegionStats> getDataConfirmed(String country){
        List<RegionStats> region_list = new ArrayList<>();

        for(RegionStats r_list: getList()){
            if (r_list.getCountry().equals(country)){
                region_list.add(r_list);
            }
        }
        return region_list;
    }

}
